document.addEventListener("DOMContentLoaded", () => {
    const $app = document.querySelector(`#app`);
    let scaleText = 1;
    let prevTimer = null;
    let isDrag = false;
    $app.addEventListener("mousedown", () => {
        isDrag = true;
        $app.classList.add("is-drag");
    });
    document.addEventListener("mousemove", (e) => {
        if (!isDrag) {
            return;
        }
        const {movementX, movementY } = e;
        const {top, right, bottom, left}   = $app.getBoundingClientRect();
        const o = new Float32Array([
            left, top, 1, 1,
            right, top, 1, 1,
            right, bottom, 1, 1,
            left, bottom, 1, 1
        ]);
        const t = new Float32Array([
            1, 0, 0, 0,
            0, 1, 0, 0,
            0, 0, 1, 0,
            movementX, movementY, 0, 1
        ]);
        let out = glMatrix.mat4.multiply(new Float32Array([
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0
        ]), t, o);
        $app.setAttribute("style", `left: ${out[0]}px; top: ${out[1]}px;width: ${out[4] - out[0]}px;height: ${out[9] - out[1]}px;transform: none;`);
    });

    document.addEventListener("mouseup", () => {
        isDrag = false;
        $app.classList.remove("is-drag");
    });

    $app.addEventListener("wheel", (e) => {
        if (!prevTimer) {
            clearTimeout(prevTimer)
        }
        const {clientX, clientY, deltaY } = e;
        let scale = 1 + (deltaY < 0 ? 0.1 : -0.1);
        scale = Math.max(scale > 0 ? scale : 1, 0.1);
        scaleText *= scale;
        const {top, right, bottom, left}   = $app.getBoundingClientRect();
        const o = new Float32Array([
            left, top, 1, 1,
            right, top, 1, 1,
            right, bottom, 1, 1,
            left, bottom, 1, 1
        ]);
        const x = clientX * (1 - scale);
        const y = clientY * (1 - scale);
        const t = new Float32Array([
            scale, 0, 0, 0,
            0, scale, 0, 0,
            0, 0, 1, 0,
            0, 0, 0, 1
        ]);
        const m = new Float32Array([
            1, 0, 0, 0,
            0, 1, 0, 0,
            0, 0, 1, 0,
            x, y, 0, 1
        ]);
        let out1 = glMatrix.mat4.multiply(new Float32Array([
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0
        ]), t, o);
        const out = glMatrix.mat4.multiply(new Float32Array([
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0
        ]), m, out1);
        $app.setAttribute("style", `left: ${out[0]}px; top: ${out[1]}px;width: ${out[4] - out[0]}px;height: ${out[9] - out[1]}px;transform: none;`);
        document.body.setAttribute("data-scale", parseInt(scaleText * 100) + "%");
        document.body.classList.add("wheel");
        prevTimer = setTimeout(() => document.body.classList.remove("wheel"), 1000);
    });
});